package com.xtravel.tweet.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.BitmapUtils;
import com.xtravel.R;
import com.xtravel.common.activity.BaseActivity;
import com.xtravel.common.activity.BrowserActivity;
import com.xtravel.common.api.BaseRequest;
import com.xtravel.common.api.domain.BaseJson;
import com.xtravel.common.constant.BrowserOpenType;
import com.xtravel.common.helper.JsonHelper;
import com.xtravel.common.helper.ShareSdkHelper;
import com.xtravel.common.widget.GridViewInnerScrollView;
import com.xtravel.common.widget.HorizontalListView;
import com.xtravel.common.widget.TweetImageView;
import com.xtravel.tweet.adapter.DestinationTravelLiveListAdapter;
import com.xtravel.tweet.adapter.ImageListAdapter;
import com.xtravel.tweet.adapter.TweetDetailHorizontalListViewAdapter;
import com.xtravel.tweet.api.TweetRequest;
import com.xtravel.tweet.database.dto.Tweet;
import com.xtravel.tweet.database.dto.TweetSource;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Kevin on 2015/10/9.
 */
public class TweetActivity extends BaseActivity {

    private Integer tweetId;
    private Activity context;
    private BitmapUtils bitmapUtils;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tweet_detail);

        this.context = this;
        this.bitmapUtils = new BitmapUtils(this);
        tweetId = getIntent().getIntExtra("tweetId", 0);
        loadTweet(tweetId);
        TextView nextTweetDetail = (TextView)findViewById(R.id.next_tweet_detail);
        nextTweetDetail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loadTweet(tweetId);
            }
        });
    }

    private void loadTweet(final Integer tweetId) {
        new AsyncTask<Void, Void, BaseJson>() {

            @Override
            protected BaseJson doInBackground(Void... params) {
                TweetRequest request = new TweetRequest();
                return request.tweet(tweetId);
            }

            @Override
            protected void onPostExecute(BaseJson json) {
                if (json != null && json.getResult() != null) {
                    Tweet tweet = (Tweet)json.getResult();
                    bindTweet(tweet);
                }
            }
        }.execute();
    }

    private void bindTweet(final Tweet tweet) {
        final Activity convertView = this;
        TextView txtTitle = (TextView) convertView.findViewById(R.id.txtTitle);
        TextView publishTime = (TextView) convertView.findViewById(R.id.publishTime);
        TextView txtMessage = (TextView) convertView.findViewById(R.id.txtMessage);
        GridView imgGrid = (GridView) convertView.findViewById(R.id.imageGrid);
        LinearLayout lyImagePannel = (LinearLayout) convertView.findViewById(R.id.lyImagePannel);
        TweetImageView imgSingle = (TweetImageView) convertView.findViewById(R.id.imageSignle);
        ImageView isHot = (ImageView) convertView.findViewById(R.id.isHot);
        LinearLayout tellFriend = (LinearLayout) convertView.findViewById(R.id.btn_tell_friend);
        LinearLayout tagsListView = (LinearLayout) convertView.findViewById(R.id.tag_container);
        final TextView retweetCountView = (TextView)convertView.findViewById(R.id.retweetCount);
        final TextView likeCountView = (TextView)convertView.findViewById(R.id.likeCount);
        final TextView wantToGoView = (TextView)convertView.findViewById(R.id.want_to_go);
        final LinearLayout liveLayout = (LinearLayout)convertView.findViewById(R.id.live_layout);
        final LinearLayout wanToGoLayout = (LinearLayout)convertView.findViewById(R.id.want_to_go_layout);
        final ImageView likeCountImg = (ImageView)convertView.findViewById(R.id.like_count_img);
        final HorizontalListView horizontalListView = (HorizontalListView)convertView.findViewById(R.id.want_to_go_horizontallist);
        GridView destinationTravelLiveGrid = (GridViewInnerScrollView)convertView.findViewById(R.id.destination_travel_live);
        //设置tag
        if(tweet.tags != null && tweet.tags.length() > 0) {
            tagsListView.removeAllViews();
            Drawable bg = context.getResources().getDrawable(R.drawable.ic_tweet_tag);
            int cl = context.getResources().getColor(R.color.cl_tweet_tag);
            String[] tagList = tweet.tags.split(" ");
            for (String tag : tagList) {
                TextView tagView = new TextView(context);
                tagView.setText(tag);
                tagView.setBackground(bg);
                tagView.setTextSize(12);
                tagView.setTextColor(cl);
                tagView.setGravity(Gravity.CENTER);
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                lp.setMargins(0, 0, 10, 0);
                tagView.setLayoutParams(lp);
                tagsListView.addView(tagView);
            }

            tagsListView.setVisibility(View.VISIBLE);
        } else{
            tagsListView.setVisibility(View.GONE);
        }
        txtTitle.setText(tweet.title);
        publishTime.setText(getPublishTime(tweet.getOnlineTime()));
        setTextViewHTML(txtMessage, tweet);
        int hotVisible = (tweet.isPerfect ? View.VISIBLE : View.GONE);
        isHot.setVisibility(hotVisible);
        int imageVisible = (tweet.getImageSources().size() <= 1 ? View.GONE : View.VISIBLE);
        imgGrid.setVisibility(imageVisible);
        imgGrid.setAdapter(new ImageListAdapter(context, this.bitmapUtils, tweet.getImageSources()));

        //设置想去目的地旅游的人的头像
        final TweetDetailHorizontalListViewAdapter tweetDetailHorizontalListViewAdapter = new TweetDetailHorizontalListViewAdapter(this,tweet.getWisher());
        horizontalListView.setAdapter(tweetDetailHorizontalListViewAdapter);

        //设置点赞数
        wantToGoView.setText(String.valueOf(tweet.wishCount)+"人想去");
        retweetCountView.setText(String.valueOf(tweet.viewCount));
        likeCountView.setText(String.valueOf(tweet.wishCount));
        if(tweet.isWish){
            likeCountImg.setSelected(true);
        }

        wanToGoLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new AsyncTask<Void, Void, BaseJson>() {
                    @Override
                    protected BaseJson doInBackground(Void... params) {
                        BaseRequest baseRequest = new BaseRequest();
                        String response = baseRequest.api("/tweet/wish/?", tweetId);
                        return JsonHelper.fromJson(response, new TypeToken<BaseJson>() {
                        });
                    }

                    @Override
                    protected void onPostExecute(BaseJson baseJson) {
                        if (baseJson != null && baseJson.getCode() == 200) {
                            if (tweet.isWish) {
                                likeCountImg.setSelected(false);
                                tweet.isWish = false;
                                tweet.wishCount--;
                                wantToGoView.setText(String.valueOf(tweet.wishCount) + "人想去");
                                likeCountView.setText(String.valueOf(tweet.wishCount));
                            } else {
                                likeCountImg.setSelected(true);
                                tweet.isWish = true;
                                tweet.wishCount++;
                                wantToGoView.setText(String.valueOf(tweet.wishCount) + "人想去");
                                likeCountView.setText(String.valueOf(tweet.wishCount));
                            }
                        }
                    }
                }.execute();
            }
        });
        tellFriend.setTag(tweet);
        tellFriend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Tweet tweet = (Tweet) arg0.getTag();
                ArrayList<String> imgUrls = new ArrayList<>();
                if (tweet.getImageSources().size() > 0) {
                    for (TweetSource t : tweet.getImageSources()) {
                        imgUrls.add(t.largeUrl);
                    }
                }

                //内容url
                String url = String.format(convertView.getString(R.string.tweet_detail_url), tweet.id);
                ShareSdkHelper.share(convertView, convertView.getResources().getString(R.string.share_tweet_title), tweet.content, url, imgUrls);
            }
        });

        if (tweet.getImageSources().size() == 1) {
            lyImagePannel.setVisibility(View.VISIBLE);
            imgSingle.setImageUrl(bitmapUtils, tweet.getImageSources().get(0).largeUrl, 240, 240);

            imgSingle.setTag(tweet.getImageSources().get(0).largeUrl);
            imgSingle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View imageView) {
                    String imageUrl = (String) imageView.getTag();
                    Intent intent = new Intent(convertView, ImageDetailActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putStringArray("url", new String[]{imageUrl});
                    bundle.putInt("start", 0);
                    intent.putExtras(bundle);
                    convertView.startActivity(intent);
                }
            });
        } else {
            lyImagePannel.setVisibility(View.GONE);
        }
/*        List<AppLive> lives = tweet.getLives();
        lives = new ArrayList<>();
        AppLive appLive = new AppLive();
        appLive.setName("马来西亚直播");
        appLive.setCover("http://tp3.sinaimg.cn/1903012754/50/5728871029/1");
        lives.add(appLive);
        lives.add(appLive);
        lives.add(appLive);
        lives.add(appLive);
        tweet.setLives(lives);*/
        if(tweet.getLives() != null && tweet.getLives().size() > 0){
            liveLayout.setVisibility(View.VISIBLE);
            DestinationTravelLiveListAdapter destinationTravelLiveListAdapter = new DestinationTravelLiveListAdapter(this,tweet.getLives());
            destinationTravelLiveGrid.setAdapter(destinationTravelLiveListAdapter);
        }else{
            liveLayout.setVisibility(View.GONE);
        }
    }

    final Html.ImageGetter linkImageGetter = new Html.ImageGetter() {
        private HashMap<String, Drawable> cache = new HashMap<String, Drawable>();

        @Override
        public Drawable getDrawable(String source) {
            if (cache.containsKey(source))
                return cache.get(source);

            BitmapDrawable drawable = null;
            int rId = Integer.parseInt(source);
            drawable = (BitmapDrawable) context.getResources().getDrawable(rId);

            DisplayMetrics dm = new DisplayMetrics();
            ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);

            drawable.setBounds(0, (int) (-5 * dm.density), drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
            drawable.setGravity(Gravity.TOP);

            return drawable;
        }
    };

    private String getDisplayTime(Long lCreatedTime) {
        lCreatedTime = lCreatedTime == null ? 0L : lCreatedTime;
        Date createdTime = new Date(lCreatedTime);
        Date nowTime = new Date();

        Long now = nowTime.getTime();
        Long diff = now - lCreatedTime;

        Calendar oldCal = Calendar.getInstance();
        Calendar newCal = Calendar.getInstance();

        oldCal.setTime(createdTime);
        newCal.setTime(nowTime);

        if (diff < 60 * 1000) {
            return "刚刚";
        }
        if (diff < 60 * 60 * 1000) {
            return (diff / (60 * 1000)) + "分钟前";
        }
        if (newCal.get(Calendar.DAY_OF_YEAR) == oldCal.get(Calendar.DAY_OF_YEAR)) {
            return new SimpleDateFormat("HH:mm").format(createdTime);
        }
        if (Math.abs(newCal.get(Calendar.DAY_OF_YEAR) - oldCal.get(Calendar.DAY_OF_YEAR)) == 1) {
            return "昨天 " + new SimpleDateFormat("HH:mm").format(createdTime);
        }
        if (newCal.get(Calendar.YEAR) == oldCal.get(Calendar.YEAR)) {
            return new SimpleDateFormat("MM月dd日").format(createdTime);
        }

        return new SimpleDateFormat("yyyy年").format(createdTime);
    }

    private String getPublishTime(Long lCreatedTime){
        String publishTime = "";
        if(lCreatedTime != null){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");
            publishTime = sdf.format(new Date(lCreatedTime));
        }
        return publishTime;
    }

    private String parseContent(String source) {
        String destString = source;
        Pattern pattern = Pattern.compile("[a-zA-z]+://[^\\s]*?\\.(com|net|info|cn|me|tw|fr)[^\u4e00-\u9fa5\\s]*");// .compile("(http://|ftp://|https://|www){0,1}[^\u4e00-\u9fa5\\s]*?\\.(com|net|info|cn|me|tw|fr)[^\u4e00-\u9fa5\\s]*");//[a-zA-z]+://[^\\s]*");
        Matcher matcher = pattern.matcher(source);
        while (matcher.find()) {
            String r = matcher.group();
            destString = destString.replace(r, String.format("<a href='%s'><img src='%s' /></a>", r, R.drawable.img_tweet_link));
        }

        return destString;
    }

    protected void makeLinkClickable(SpannableStringBuilder strBuilder, final URLSpan span, final Tweet tweet) {
        int start = strBuilder.getSpanStart(span);
        int end = strBuilder.getSpanEnd(span);
        int flags = strBuilder.getSpanFlags(span);

        ClickableSpan clickable = new ClickableSpan() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context, BrowserActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("title", "资讯详情");
                bundle.putString("url", span.getURL());
                bundle.putString("content", tweet.content);
                bundle.putString("opentype", BrowserOpenType.Link_Share);
                //分享查看内容的链接地址
                bundle.putString("shareurl", String.format(context.getString(R.string.tweet_detail_url), tweet.id));
                bundle.putString("sharetitle", context.getResources().getString(R.string.share_tweet_title));
                ArrayList<String> imgUrls = new ArrayList<>();
                for (TweetSource t : tweet.getImageSources()) {
                    imgUrls.add(t.largeUrl);
                }

                bundle.putStringArrayList("imgurl", imgUrls);
                intent.putExtras(bundle);
                context.startActivity(intent);
            }
        };

        strBuilder.setSpan(clickable, start, end, flags);
        strBuilder.removeSpan(span);
    }

    protected void setTextViewHTML(TextView txtMessage, Tweet tweet) {
        String htmText = parseContent(tweet.content);
        CharSequence sequence = Html.fromHtml(htmText, linkImageGetter, null);
        SpannableStringBuilder strBuilder = new SpannableStringBuilder(sequence);
        URLSpan[] urls = strBuilder.getSpans(0, sequence.length(), URLSpan.class);
        for (URLSpan span : urls) {
            makeLinkClickable(strBuilder, span, tweet);
        }

        txtMessage.setMovementMethod(LinkMovementMethod.getInstance());
        txtMessage.setText(strBuilder);
    }

    public void onBack(View view) {
        setResult(1);
        finish();
        //this.onBackPressed();


    }
}
